package nero.yncc.com.createart.activity;

import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;

import org.json.JSONArray;
import org.json.JSONException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.finalteam.toolsfinal.StringUtils;
import nero.yncc.com.createart.R;
import nero.yncc.com.createart.base.BaseActivity;
import nero.yncc.com.createart.base.Constants;
import nero.yncc.com.createart.bean.AddressBean;
import nero.yncc.com.createart.bean.RegionBean;
import nero.yncc.com.createart.custom.LoopView;
import nero.yncc.com.createart.custom.OnItemSelectedListener;
import nero.yncc.com.createart.utils.HttpUtils;

@ContentView(R.layout.activity_address_edit)
public class ActivityAddressEdit extends BaseActivity {

    @ViewInject(R.id.ll_location)
    LinearLayout ll_location;
    @ViewInject(R.id.et_name)
    EditText et_name;
    @ViewInject(R.id.et_phone)
    EditText et_phone;
    @ViewInject(R.id.tv_location)
    TextView tv_location;
    @ViewInject(R.id.et_address)
    EditText et_address;
    @ViewInject(R.id.btn_save)
    Button btn_save;

    TextView tv_choose_address;
    private PopupWindow mPopupWindow;
    private LoopView loopView1, loopView2, loopView3;

    private List<String> firstList = new ArrayList<>();
    private List<String> secondList = new ArrayList<>();
    private List<String> thirdList = new ArrayList<>();

    private ArrayList<RegionBean> arrayList_first = new ArrayList<>();
    private ArrayList<RegionBean> arrayList_second = new ArrayList<>();
    private ArrayList<RegionBean> arrlistEnd = new ArrayList<>();

    private String cityID;
    private String proID;
    private String districtID;

    private View popView;

    String address_id;
    String firstArea, secondArea, thirdArea;

    @Override
    protected void initView() {
        setTitleBarTitle("收货地址");

        address_id = getIntent().getStringExtra("address_id");

        AddressBean addressBean = (AddressBean) getIntent().getSerializableExtra("address_id");
        if (addressBean != null) {
            et_name.setText(addressBean.getConsignee());
            et_phone.setText(addressBean.getMobile());
            address_id = addressBean.getAddress_id();

            firstArea = addressBean.getProvince();
            proID = addressBean.getProvinceid();
            secondArea = addressBean.getCity();
            cityID = addressBean.getCityid();
            thirdArea = addressBean.getDistrict();
            districtID = addressBean.getDistrictid();

            tv_location.setText(firstArea + " " + secondArea + " " + thirdArea);
            et_address.setText(addressBean.getAddress());
        }
        popView = View.inflate(this, R.layout.layout_pop_loopview, null);
        loopView1 = popView.findViewById(R.id.consignee_lpv1);
        loopView2 = popView.findViewById(R.id.consignee_lpv2);
        loopView3 = popView.findViewById(R.id.consignee_lpv3);

        initPopWindow();
    }


    @Override
    protected void initData() {
        getFirstLevelData();
    }

    @Override
    protected void initListener() {
        ll_location.setOnClickListener(this);
        btn_save.setOnClickListener(this);
        tv_choose_address.setOnClickListener(this);
    }

    @Override
    protected void doClick(int id) {
        super.doClick(id);
        switch (id) {
            case R.id.ll_location:
                showPopWIndow();
                break;
            case R.id.btn_save:
                addAddress();
                break;
            case R.id.tv_choose_address:
                tv_location.setText(firstArea + " " + secondArea + " " + thirdArea);
                mPopupWindow.dismiss();
                break;
        }
    }


    String name;
    String phone;
    String location;
    String address;

    /**
     * 添加地址
     * consignee
     * mobile
     * district
     * cityId,
     * province
     * user_id
     * address
     */
    private void addAddress() {
        name = et_name.getText().toString();
        phone = et_phone.getText().toString();
        location = tv_location.getText().toString();
        address = et_address.getText().toString();

        if (StringUtils.isEmpty(name)) {
            Toast.makeText(this, "收件人姓名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtils.isEmpty(phone)) {
            Toast.makeText(this, "收件人电话不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (StringUtils.isEmpty(firstArea)) {
            Toast.makeText(this, "未选择省份", Toast.LENGTH_SHORT).show();
            return;
        }

        if (StringUtils.isEmpty(secondArea)) {
            Toast.makeText(this, "未选择市区", Toast.LENGTH_SHORT).show();
            return;
        }

        if (StringUtils.isEmpty(thirdArea)) {
            Toast.makeText(this, "未选择地区", Toast.LENGTH_SHORT).show();
            return;
        }

        if (StringUtils.isEmpty(address)) {
            Toast.makeText(this, "未填写详细地址", Toast.LENGTH_SHORT).show();
            return;
        }
        showProgress("正在添加地址...");
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("consignee", name);
        hashMap.put("mobile", phone);
        hashMap.put("user_id", userBean.getUser_id());
        hashMap.put("address", address);
        hashMap.put("address_id", address_id);//修改时使用
        hashMap.put("province", proID);
        hashMap.put("city", cityID + "");
        hashMap.put("district", districtID + "");

        new HttpUtils().post(this, Constants.API_ADDADDRESS, hashMap, null, HttpUtils.TYPE_NOTHING, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                showToast(msg);
                hideProgress();
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void fail(String failMsg) {
                hideProgress();
                showToast(failMsg);
            }
        });


    }

    /**
     * 弹出修改密码的popupwindow
     */
    private void initPopWindow() {

        popView = View.inflate(this, R.layout.layout_pop_loopview, null);
        loopView1 = popView.findViewById(R.id.consignee_lpv1);
        loopView2 = popView.findViewById(R.id.consignee_lpv2);
        loopView3 = popView.findViewById(R.id.consignee_lpv3);
        tv_choose_address = popView.findViewById(R.id.tv_choose_address);
        popView.findViewById(R.id.ll_root).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                chooseArea.setText(firstArea + " " + secondArea + " " + thirdArea);
                if (mPopupWindow != null) {
                    mPopupWindow.dismiss();
                }
            }
        });

        loopView1.setNotLoop();
        loopView1.setTextSize(15);
        loopView1.setCenterTextColor(R.color.colorAccent);
        loopView1.setOuterTextColor(R.color.colorPrimary);
        loopView1.setItemsVisibleCount(4);

        loopView2.setNotLoop();
        loopView2.setTextSize(15);
        loopView2.setCenterTextColor(R.color.colorAccent);
        loopView2.setOuterTextColor(R.color.colorPrimary);
        loopView2.setItemsVisibleCount(4);

        loopView3.setNotLoop();
        loopView3.setTextSize(15);
        loopView3.setCenterTextColor(R.color.colorAccent);
        loopView3.setOuterTextColor(R.color.colorPrimary);
        loopView3.setItemsVisibleCount(4);

        loopView1.setListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                try {
                    firstArea = arrayList_first.get(index).getName();
                    proID = arrayList_first.get(index).getId();
                    loopView2.setVisibility(View.INVISIBLE);
                    loopView3.setVisibility(View.INVISIBLE);
                    getNextLvDataByID(proID, "2");
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
        loopView2.setListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                try {
                    secondArea = arrayList_second.get(index).getName();
                    cityID = arrayList_second.get(index).getId();
                    loopView3.setVisibility(View.INVISIBLE);
                    getNextLvDataByID(cityID, "3");

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        loopView3.setListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                thirdArea = arrlistEnd.get(index).getName();
                districtID = arrlistEnd.get(index).getId();
            }
        });

        mPopupWindow = new PopupWindow(popView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, false);
        mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        mPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        mPopupWindow.setAnimationStyle(R.style.pop_anmi_bottombar);
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams params = getWindow().getAttributes();
                params.alpha = 1f;
                getWindow().setAttributes(params);
            }
        });

    }

    private void showPopWIndow() {
        mPopupWindow.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.3f;
        getWindow().setAttributes(params);
    }


    /**
     * 获取第一级地区数据省直辖市
     */
    private void getFirstLevelData() {

        HashMap<String, String> hashMap = new HashMap<>();
        HttpUtils.get(this, Constants.API_GETLOCAL, hashMap, null, HttpUtils.TYPE_ARRAY, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                JSONArray jsonArray = (JSONArray) json;
                firstList.clear();
                arrayList_first.clear();

                for (int i = 0; i < jsonArray.length(); i++) {
                    try {
                        RegionBean bean = JSON.parseObject(jsonArray.getString(i), RegionBean.class);
                        firstList.add(bean.getName());
                        arrayList_first.add(bean);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                //初始化选择的第一级数据
                if (arrayList_first.size() > 0) {
                    loopView1.setItems(firstList);
                    proID = arrayList_first.get(0).getId();
                    firstArea = arrayList_first.get(0).getName();
                    getNextLvDataByID(proID + "", "2");
                }

            }

            @Override
            public void fail(String failMsg) {

            }
        });
    }


    /**
     * 获取下一级数据
     *
     * @param pid
     * @param level
     */
    private void getNextLvDataByID(String pid, String level) {
        HashMap<String, String> params = new HashMap();
        params.put("pid", pid);
        params.put("level", level);
        final String level_fin = level;
        HttpUtils.get(this, Constants.API_GETLOCAL, params, null, HttpUtils.TYPE_ARRAY, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {

                if (level_fin.equals("2")) {
                    JSONArray jsonArray = (JSONArray) json;
                    secondList.clear();
                    arrayList_second.clear();
                    for (int i = 0; i < jsonArray.length(); i++) {
                        try {
                            RegionBean regionBean = JSON.parseObject(jsonArray.getString(i), RegionBean.class);
                            secondList.add(String.valueOf(regionBean.getName()));
                            arrayList_second.add(regionBean);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    //初始化二级地区数据
                    cityID = arrayList_second.get(0).getId();
                    secondArea = arrayList_second.get(0).getName();
                    getNextLvDataByID(cityID + "", "3");

                    loopView2.setVisibility(View.VISIBLE);
                    loopView2.setItems(secondList);
                    loopView2.setCurrentPosition(0);
                } else if (level_fin.equals("3")) {
                    JSONArray jsonArray = (JSONArray) json;
                    thirdList.clear();
                    arrlistEnd.clear();
                    for (int i = 0; i < jsonArray.length(); i++) {
                        RegionBean regionBean = null;
                        try {
                            regionBean = JSON.parseObject(jsonArray.getString(i), RegionBean.class);
                            thirdList.add(String.valueOf(regionBean.getName()));
                            arrlistEnd.add(regionBean);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                    //初始化三级地区数据
                    thirdArea = arrlistEnd.get(0).getName();
                    districtID = arrlistEnd.get(0).getId();
                    loopView3.setVisibility(View.VISIBLE);
                    loopView3.setItems(thirdList);
                    loopView3.setCurrentPosition(0);
                }

            }

            @Override
            public void fail(String failMsg) {

            }
        });

    }

}
